package com.situ.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.user.bean.User;
import com.situ.user.mapper.UserMapper;
import com.situ.user.service.UserService;
import com.situ.user.utils.MD5Util;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 
	 * @author: JavaSiegeLoin(Gang)
	 * @创建日期: 2021年10月20日 下午3:53:18
	 * @Title: reg
	 * @throws:
	 * @类描述-Description: 用户的注册
	 */
	@Override
	public int reg(User user, String repassword) {
		// 验证格式
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			return -1;
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			return -2;
		}
		// 比较两次密码是否一致
		if (!user.getPassword().equals(repassword)) {
			return -3;
		}
		// 比较账号是否可用
		User selectUser = userMapper.selectByUsername(user.getUsername());
		if (selectUser != null) {
			return -4;
		}
		// 写入数据库
		user.setPassword(MD5Util.getMD5(repassword));
		return userMapper.insert(user);
	}

	@Override
	public User login(User user) throws Exception {
		// 验证格式
		if (user.getUsername().length() < 3 || user.getUsername().length() > 16) {
			throw new Exception("账号格式不对！！");
		}
		if (user.getPassword().length() < 3 || user.getPassword().length() > 16) {
			throw new Exception("密码格式不对！！");
		}
		User selectUser = userMapper.selectByUsername(user.getUsername());
		if (selectUser == null) {
			throw new Exception("账号不存在！！");
		}
		// 密码
		if (!selectUser.getPassword().equals(MD5Util.getMD5(user.getPassword()))) {
			throw new Exception("密码不正确！！");
		}

		// 用户的状态
		if (selectUser.getStatus() == 1) {
			throw new Exception("账号已被禁用！！请联系管理员");
		}

		return selectUser;
	}

}
